<?php
use Thenbsp\Wechat\OAuth\Client;
use Thenbsp\Wechat\Wechat\Jsapi;
use Thenbsp\Wechat\Wechat\AccessToken;
class ApiController extends WechatController {

	const LIST_KEY = 'roomlist';
	const INFO_KEY = 'room:';
	const MAX_POS = 4;
	const DEFAULT_POINT = 10000;
	const MAX_POINT = 4;
	const VALID_TIME = 20;
	//玩家状态
	const STATE_NONE = 0;
	const STATE_READY = 1;
	const STATE_PLAYING = 2;
	const PLAYER_ORDER ='player_order::';
	const LIST_USER='userlist';

	private $user;

	public function init()
	{	
		parent::init();
		$this->mUser = new UserModel(null,false);
		$this->mUser->getUidByFromuser($this->fromuser);
		$this->user = $this->mUser->getInfo();
	}
	/**
	 * 微信密钥
	 * [wechatSecret description]
	 * @return [type] [description]
	 */
	public function wechatSecretAction(){
		// $access_token=get_access_token();
		// $jsapi_ticket=get_jsapi_ticket($access_token);
		// $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
		// $url = $url?$url:"$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
		// //$url =str_replace('game.newshise.com:8000','wx.xxxing.cn/game',$url);
		// $timestamp = time();
		// $nonceStr = createNonceStr();
		// $string = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
		// $signature = sha1($string);
		// $signPackage = array(
		// 	  "appId"     => ,
		// 	  "nonceStr"  => $nonceStr,
		// 	  "timestamp" => $timestamp,
		// 	  "url"       => $url,
		// 	  "signature" => $signature,
		// 	  "rawString" => $string,
		// 	);
		$url =$_GET['url'];
		$url="http://www.nbpipixia.cn/mahjong/";
		$config_wechat=$this->config->wechat->toArray();
		$config_database =$this->config->database->config->toArray();
	    $appid =$config_wechat['appid'];
		$appsecret=$config_wechat['appsecret'];
		$client = new Client($appid, $appsecret);
		$accessToken = new AccessToken($appid,$appsecret);
		$new_redis =RedisDB::factory('accesstoken');
		$cacheDriver = new \Doctrine\Common\Cache\RedisCache();
		$cacheDriver->setRedis($new_redis);
		$accessToken->setCache($cacheDriver);
		$access_token =$accessToken->getTokenString();
		$jsapi = new Jsapi($accessToken);
		$jsapi->setCache($cacheDriver);
		$jsapi->url=$url;
		//$jsapi->addApi('onMenuShareTimeline')->addApi('onMenuShareAppMessage');
		$signPackage = $jsapi->getConfig();

		$data =array('success'=>0,'signPackage'=>$signPackage);
		$this->response(200,'微信config信息',$data);
	}
	public function wechatGameAction()
	{
		//$url ="http://www.nbpipixia.cn/game/index.html";
		$url =$_POST['url'];
		$config_wechat=$this->config->wechat->toArray();
		$config_database =$this->config->database->config->toArray();
	    $appid =$config_wechat['appid'];
		$appsecret=$config_wechat['appsecret'];
		$client = new Client($appid, $appsecret);
		$accessToken = new AccessToken($appid,$appsecret);
		$new_redis =RedisDB::factory('accesstoken');
		$cacheDriver = new \Doctrine\Common\Cache\RedisCache();
		$cacheDriver->setRedis($new_redis);
		$accessToken->setCache($cacheDriver);
		$access_token =$accessToken->getTokenString();
		$jsapi = new Jsapi($accessToken);
		$jsapi->setCache($cacheDriver);
		$jsapi->url=$url;
		//$jsapi->addApi('onMenuShareTimeline')->addApi('onMenuShareAppMessage');
		$signPackage = $jsapi->getConfig(true);

		$data =array('success'=>0,'signPackage'=>$signPackage);
		$this->response(200,'游戏页面config信息',$data);
	}
	/**
	 * 判断房间是否存在
	 * [existRoomAction description]
	 * @return [type] [description]
	 */
	public function existRoomAction(){
		$request_roomid =$_GET['roomid'];
		if(!$request_roomid){
			$data =array('roomid'=>$request_roomid);	
			$this->response(401,'房间号不存在',$data);
		}
		$roomlist = $this->redis->hGetAll(self::LIST_KEY);
		$isExist=false;
		if(is_array($roomlist)&&$roomlist){
			foreach ($roomlist as $roomid => $value) {
				if($roomid ==$request_roomid){
					$isExist=true;
					break;
				}
			}
		}
		if($isExist){
			$data =array('roomid'=>$request_roomid);	
			$this->response(200,'房间号存在',$data);
		}else{
			$data =array('roomid'=>$request_roomid);	
			$this->response(401,'房间号不存在',$data);
		}
		
	}
	public function myjoinAction(){
		$roomlist = $this->redis->hGetAll(self::LIST_KEY);
		$myjoin_room = array();
		if(is_array($roomlist)&&$roomlist){
			foreach ($roomlist as $roomid => $value) {
					$this_roominfo = json_decode($value,true);
					$uid = $this->mUser->getUidByFromuser($this->fromuser);
					if($uid){
						$mUser = new UserModel($uid);
						$this_userinfo =$mUser->getInfo();
					}
					if($this_roominfo['time_way']==1){
						$end_time = $this_roominfo['created']+$this_roominfo['setting_value'];
						$minute_second=date('H:i',$end_time);
					}else{
						$minute_second =$this_roominfo['setting_value'].'圈';
					}

					$myjoin_room[] =array(
							'roomid'=>$roomid,
							'game_type'=>$this_roominfo['game_type'],
							'time_way'=>$this_roominfo['time_way'],//1-时间 2-圈数
							'time_value'=>$this_roominfo['setting_value'],//20分钟
							'headimgurl'=>$this_userinfo['headimgurl'],
							'month_day'=>date('m-d',$this_roominfo['created']),
							'minute_second'=>$minute_second,
						);
			}
		}
		$userInfo = $this->user;		
		if($userInfo['roomid']){
			$roomInfo =$this->redis->hGetAll(self::LIST_KEY,$userInfo['roomid']);
			if(is_array($roomInfo) && $roomInfo){
					if($roomInfo['time_way']==1){
						$end_time = $roomInfo['created']+$roomInfo['setting_value'];
						$minute_second=date('H:i',$end_time);
					}else{
						$minute_second =$roomInfo['setting_value'].'圈';
					}

				$myjoining[] =array(
							'roomid'=>$userInfo['roomid'],
							'game_type'=>$roomInfo['game_type'],
							'time_way'=>$roomInfo['time_way'],//1-时间 2-圈数
							'time_value'=>$roomInfo['setting_value'],//20分钟
							'headimgurl'=>$this_userinfo['headimgurl'],
							'month_day'=>date('m-d',$this_userinfo['created']),
							'minute_second'=>$minute_second,
				);
			}
			
		}
		
		$this->response(200,'我的房间信息',array('mycreate'=>$myjoin_room,'myjoining'=>$myjoining));
	}
	public function ageAction(){
		$roomid =$_GET['roomid'];			
		$this->redis=RedisDB::factory('game');
		$dachu = $this->redis->hGetAll(self::INFO_KEY.$roomid);
		$this->redis->hDel(self::INFO_KEY.$roomid);
		echo json_encode($dachu);exit;
		/* $mypai =array(12,12,31,32,33);
		echo $isHu=$this->basicHu($mypai); */
		
		/* $gang_pai=array();
		foreach($mypai as $next){
				$is_ok = $this->findPai($mypai,$next);
				if($is_ok){
					$gang_pai[]=$next;
				}
		}
		$combox_gang_pai=array();
		$count =count($gang_pai);
		for($i=0;$i<$count;$i++){
			if($i%4==0){
				$this_gang_arr = array($gang_pai[$i],$gang_pai[$i],$gang_pai[$i],$gang_pai[$i]);
				$combox_gang_pai[]= implode(',',$this_gang_arr);
			}
		} */
		//print_r($combox_gang_pai);
	/* 	$user = $this->user;
		$game = new ElephantajiangModel($this->mUser , $user['roomid']);
		$scorelist =array(
				1=>array(
							'nickname'=>'aa',
							'headimgurl'=>'',
							'score'=>10,
							'pai'=>7,
							'basic_score'=>10,
					),
				2=>array(
							'nickname'=>'bb',
							'headimgurl'=>'',
							'score'=>0,
							'pai'=>7,
							'basic_score'=>0,
					),
				3=>array(
							'nickname'=>'cc',
							'headimgurl'=>'',
							'score'=>-10,
							'pai'=>7,
							'basic_score'=>-10,
					),
				4=>array(
							'nickname'=>'dd',
							'headimgurl'=>'',
							'score'=>0,
							'pai'=>7,
							'basic_score'=>0,
					),
			);
		$list =array(
							'front_pai'=>array(6,6,6,13,13,13,21,22,23),
							'handpai'=>array(2,2),
							'pai_type'=>array(array('title'=>'aa'),array('title'=>'ye')),
							'all_taishu'=>25,
							'pai'=>2,
							'scorelist'=>$scorelist,
						);
		$game->changeUserScore($list); */
	}
	public function bannerAction(){
		$database_config =$this->config->database->config->toArray();
		$prefix =$database_config['prefix'];
		$bannerTable =new HbModel($prefix.'banners');
		$sql="SELECT *  FROM gm_banners ORDER BY id DESC LIMIT 5";
		$res=$bannerTable->query($sql);
		$temp_list=array();
		if(is_array($res)&&$res){
			foreach ($res as $key => $value) {
				$value['pic']='/admin/Public/adm/h-ui/lib/webuploader/0.1.5/server/upload/'.$value['pic'];
				$temp_list[]=$value;
			}
		}
		$this->response(200,'幻灯片列表',$temp_list);
	}
	public function getfeedbackAction(){
		$uid = $this->mUser->getUid();
		$database_config =$this->config->database->config->toArray();
		$prefix =$database_config['prefix'];
		$bannerTable =new HbModel($prefix.'banners');
		$sql="SELECT *  FROM gm_feedback WHERE uid=".$uid." ORDER BY id DESC ";
		$res=$bannerTable->query($sql);
		$temp_list=array();
		if(is_array($res)&&$res){
			foreach ($res as $key => $value) {
				$value['created']=date('Y-m-d H:i:s',$value['created']);
				$temp_list[]=$value;
			}
		}
		$this->response(200,'我的留言列表',$temp_list);
	}
	public function feedbackAction(){
		$uid = $this->mUser->getUid();
		$username =$_POST['username'];
		$phone = $_POST['phone'];//$this->getRequest()->getQuery('phone');
		$question = $_POST['question'];//$this->getRequest()->getQuery('question');
		$kind = $_POST['kind'];//$this->getRequest()->getQuery('kind');
		$type_id =$_POST['type_id'] ;//$this->getRequest()->getQuery('type_id');

		$save_data=array(
				'uid'=>$uid,
				'username'=>$username,
				'phone'=>$phone,
				'question'=>$question,
				'kind'=>$kind,
				'type_id'=>$type_id,
				'created'=>time(),
			);
		$config_obj=Yaf_Registry::get("config");
		$config_database =$config_obj->database->config->toArray();
		$prefix =$config_database['prefix'];
		$feedbackTable =new HbModel($prefix.'feedback');
		$res=$feedbackTable->add($save_data);
		if($res){
			//反馈成功
			$this->response(200,'反馈成功','');
		}else{
			$this->response(401,'反馈失败','');
		}
	}

	public function goldPayAction(){
		$config_obj=Yaf_Registry::get("config");
		$config_database =$config_obj->database->config->toArray();
		$prefix =$config_database['prefix'];
		$goldTypesTable =new HbModel($prefix.'gold_types');
		$sql="SELECT *  FROM gm_gold_types ORDER BY price ASC";
		$res=$goldTypesTable->query($sql);
		$this->response(200,'钻石充值价格类目表',$res);
	}
	public function userinfoAction(){
		$user = $this->user;
		$uid =$user['uid'];
		$level =new LevelModel($uid);
		$levelInfo = $level->getLevel();
		$userInfo=array(
				'uid'=>$uid,
				'fromuser'=>$this->fromuser,
				'nickname'=>$user['nickname'],
				'headimgurl'=>$user['headimgurl'],
				'title'=>$levelInfo['title'],
				'gold'=>$user['gold'],
				'point'=>$user['point'],
				'pay_amount'=>$levelInfo['pay_amount'],
				'discount'=>$levelInfo['discount'],
				'roomid'=>isset($user['roomid'])&&$user['roomid']?$user['roomid']:'',
			);
		$this->response(200,'用户信息',$userInfo);

	}
	public function meAction(){
		$user = $this->user;
		$mMatch =new MatchModel($user['uid']);
		$game = new ElephantajiangModel($this->mUser , $user['roomid']);
		$room = $game->getInfoEx();
		$player=array(
				array(
						'score'=>'23',
						'uid'=>1,
					),
				array(
						'score'=>'0',
						'uid'=>16,
					),
				array(
						'score'=>'-5',
						'uid'=>18,
					),
				array(
						'score'=>'6',
						'uid'=>19,
					),
			);
		$mMatch->saveUserMatch($room,$player);
	}
	public function matchAction(){
		$ways =isset($_GET['ways'])&&intval($_GET['ways'])==2?2:1;//1-牌局统计 2-战绩统计
		$uid = $this->mUser->getUid();
		$mMatch =new MatchModel($uid);
		//$mMatch->delete();
		// $match_data[] = array(
		// 		'match'=>1,
		// 		'game_type'=>'xizhou',
		// 		'time_way'=>1,
		// 		'time_value'=>20,
		// 		'score'=>20,
		// 		'detail'=>array(
		// 				'roomid'=>'2012322',
		// 				'owner'=>'1',
		// 				'created'=>'1496326869',
		// 				'player'=>array(
		// 						array(									
		// 							'score'=>5,
		// 							'uid'=>17,
		// 							),
		// 						array(
		// 							'score'=>-20,
		// 							'uid'=>2,									
		// 							),
		// 						array(
		// 							'score'=>0,
		// 							'uid'=>10,									
		// 							),
		// 						array(
		// 							'score'=>14,
		// 							'uid'=>4,
									
		// 							),
		// 					),
		// 				'watcher'=>array(
		// 						array(
		// 								'uid'=>18,
		// 							),
		// 						array(
		// 								'uid'=>19,
		// 							),
		// 					),
		// 			),
		// 	);
		// $match_data[] = array(
		// 		'match'=>2,
		// 		'game_type'=>'xizhou',
		// 		'time_way'=>1,
		// 		'time_value'=>20,
		// 		'score'=>-4,
		// 		'detail'=>array(
		// 				'roomid'=>'2012322',
		// 				'owner'=>1,
		// 				'created'=>'1496326869',
		// 				'player'=>array(
		// 						array(
		// 							'score'=>-4,
		// 							'uid'=>2,
		// 							),
		// 						array(
		// 							'score'=>6,
		// 							'uid'=>4,
										
		// 							),
		// 					),
		// 			),
		// 	);
		// $match_data_arr['list']=json_encode($match_data);
		// $mMatch->save($match_data_arr);
		$s=$mMatch->getMacth();
		$out =json_decode($s['list']);
		$total=0;
		$xizhou_numbers=0;
		$dancheng =0;
		$dancheng_victory=0;
		$xizhou_victory=0;
		$all_score=0;
		$max_score = array();
		$min_score = array();
		$my_game =array();
		foreach($out as $key=>$v){
			$total++;
			$all_score+=$v->score;
			if($v->score>0){
				array_push($max_score, $v->score);
			}elseif($v->score<0){
				array_push($min_score, $v->score);
			}
			if($v->game_type=="xizhou"){
				$xizhou_numbers++;
				if($v->score>0) $xizhou_victory++;
			}elseif($v->game_type=="dancheng"){
				$dancheng++;
				if($v->score>0) $dancheng_victory++;
			}
			$this_game_detail =$v->detail;
			$userInfo =$this->mUser->getInfo();
			$headimgurl =$userInfo['headimgurl'];
			$nickname =$userInfo['nickname'];
			$my_game[]=array(
					'roomid'=>$this_game_detail->roomid,
					'created'=>$this_game_detail->created?date('Y-m-d H:i:s',$this_game_detail->created):'',
					'game_type'=>$v->game_type,
					'time_way'=>$v->time_way,
					'time_value'=>$v->time_value,
					'score'=>$v->score,
					'headimgurl'=>$headimgurl,
					'nickname'=>$nickname,
					'match_id'=>$v->match,
				);
		}
		$game_list=array();
		if($xizhou_numbers>0){
			$percent =($xizhou_victory/$xizhou_numbers);
			$percent =sprintf('%.2f',$percent);
			$game_list=array('xizhou'=>array('numbers'=>$xizhou_numbers,'percent'=>$percent));
		}elseif($dancheng>0){
			$percent= ($dancheng_victory/$dancheng);
			$percent =sprintf('%.2f',$percent);
			$game_list=array('dancheng'=>array('numbers'=>$dancheng,'percent'=>$percent));
		}

		if($ways==2){
			sort($min_score);
			sort($max_score);
			$pao_score =is_array($min_score)&&$min_score?array_shift($min_score):0;
			$hu_score =is_array($max_score)&&$max_score?array_pop($max_score):0;
			$response=array(
				'all_score'=>$all_score,
				'hu_score'=>$hu_score,
				'pao_score'=>abs($pao_score),
				'my_game'=>$my_game,
			);

		}else{
			$wins =$xizhou_victory+$dancheng_victory;
			$victory_percent= sprintf('%.2f',$wins/$total);
			$response=array(
			'total'=>$total,
			'victory_percent'=>$victory_percent,
			);
			$response =array_merge($response,$game_list);
		}
		
		$message =$ways==2?'战绩统计':'牌局统计';
		$this->response(200,$message,$response);


	}
	/**
	 * 牌局详情
	 * [gamblingAction description]
	 * @return [type] [description]
	 */
	public function gamblingAction(){
		$match_id = $this->getRequest()->getQuery('match_id');
		if(!$match_id) $this->response(401,'match_id 为空.','');
		$uid = $this->mUser->getUid();
		$mMatch =new MatchModel($uid);
		$s=$mMatch->getMacth();
		$out =json_decode($s['list']);
		//找出当前的比赛信息
		$this_matchInfo =array();
		if(is_array($out)&&$out){
			foreach($out as $next){
				if($next->match==$match_id){
					$this_matchInfo = $next;
					break;
				}
			}
		}
		if(!$this_matchInfo) $this->response(401,'比赛信息不存在.','');
		$game_type =$this_matchInfo->game_type;
		$detail =$this_matchInfo->detail;
		$owner = $detail->owner;//房主
		$this->mUser = new UserModel($owner);
		$ownerInfo = $this->mUser->getInfo();
		$player =$detail->player;
		$watcher =$detail->watcher;
		if(is_array($watcher)&&$watcher){
			foreach ($watcher as $key => $value) {
				$userInfo =$this->getUserInfo($value->uid);
				$watcher_arr[]=array(
						'nickname'=>$userInfo['nickname'],
						'headimgurl'=>$userInfo['headimgurl'],
						'score'=>0,
					);
			}
		}
		arsort($player);//积分排序
		$now_key=0;
		if(is_array($player)&&$player){
			foreach($player as $p){
				if(!isset($p->uid)) continue;
				$now_uid =$p->uid;
				++$now_key;
				$this_score=$p->score;
				if($now_key>=3 && !$this_score){
					if(is_array($watcher_arr)&&$watcher_arr){
						foreach ($watcher_arr as $key => $value) {
							$user_list[]=$value;
						}
					}
				}
				$userInfo =$this->getUserInfo($now_uid);
				$user_list[]=array(
						'nickname'=>$userInfo['nickname'],
						'headimgurl'=>$userInfo['headimgurl'],
						'score'=>$p->score,
					);
			}
		}
		$mymatchInfo =array(
				'owner_headimgurl'=>$ownerInfo['headimgurl'],
				'owner_nickname'=>$ownerInfo['nickname'],
				'time_way'=>$this_matchInfo->time_way,
				'time_value'=>$this_matchInfo->time_value,
				'created'=>$detail->created?date('Y-m-d H:i:s',$detail->created):'',
				'game_type'=>$game_type,
				'roomid'=>$detail->roomid,
				'user_list'=>$user_list,
			);
		$message ='比赛详情';
		$this->response(200,$message,$mymatchInfo);
	}
	private function getUserInfo($uid){
		$this->mUser = new UserModel($uid);
		$userInfo = $this->mUser->getInfo();
		return $userInfo;
	}
	public function goAction(){
		$this->redis = RedisDB::factory('user');
		$userlist = $this->redis->hGetAll(self::LIST_USER);
		if(is_array($userlist) && $userlist){
			foreach($userlist as $cur_uid=>$user){
				$userInfo =json_decode($user,true);
				
				$uid =$userInfo['uid'];
				$mUser = new UserModel($uid);
				$user_info=$mUser->getInfo();
				$user_info['roomid']='';
				$user_info['seatid']='';
				$mUser->save($user_info);
			}
		}
			
			$this->redis = RedisDB::factory('game');
			$roomlist = $this->redis->hGetAll(self::LIST_KEY);
			foreach ($roomlist as $key => $value) {
				$this->redis->hDel(self::LIST_KEY,$key);
			}
			print_r($roomlist);exit;			
			// $seatkey = 'seat4';
			// $next_pai=array(3,11,12,12,12,15,16,21,25,26,33,33,33);
			// $new_gang_pai =array(33,33,33,33);
			// $seat_list = $this->redis->hGet(self::INFO_KEY.$roomid,$seatkey);
			// $seat_list =json_decode($seat_list);
			// $front_list = $seat_list->front?array_merge($seat_list->front,$new_gang_pai):$new_gang_pai;
			// $present_gang =$seat_list->gang?$seat_list->gang->$throw_seatid:0;
			// $seat_list->front=$front_list;

			// $now_throw_front = $seat_list->throw_front;
			// array_pop($now_throw_front);
			// $seat_list->throw_front=$now_throw_front;//删除最后一个牌

			// $seat_list->$seatkey= $next_pai;
			// $now_present_gang = ++$present_gang;
			// $seat_list->waiter_doing=array();//清空
			// $seat_list->gang = array($throw_seatid=>$now_present_gang);
			// $seat_list->player_action=array('gang'=>$throw_seatid);//自己摸牌杠的还是拿别人的牌杠的
			// $upsert["$seatkey"]=  json_encode($seat_list);

			// print_r($seat_list);exit;



			// $info=$this->redis->hGetAll(self::PLAYER_ORDER . $roomid);
			// $checkorder =json_decode($info['order'],true);

			//print_r($order);exit;
			$dachu = $this->redis->hGetAll(self::INFO_KEY.$roomid);
			// $upsert['point']=10;
			// $this->redis->hMSet(self::INFO_KEY . $roomid,$upsert);

			// $throw_order_org =isset($dachu['throw_order'])?$dachu['throw_order']:'';
			// if($throw_order_org){
			// 	$throw_order_org =json_decode($throw_order_org,true);
			// 	$all_arr=$throw_order_org;
			// }
			// $all_arr[] = array(15=>2);
			

			// $dachu['throw_order']= json_encode($all_arr);
			// $this->redis->hMSet(self::INFO_KEY . $roomid,$dachu);
			// $next_user = json_decode($dachu['seat1'],true);
			// print_r($next_user);exit;
			// $out =json_decode($dachu['seat4'],true);
			// print_r($out);exit;
			//$elephantModel=new ElephantajiangModel($mUser,$roomid);
			//echo $mGame->getUidBySeatid(3);
			// $info =$elephantModel->getInfo();
			// unset($info['desk_majiang']);
			// unset($info['dachu']);
			// unset($info['left_pai']);
			// for($i=1;$i<=4;$i++){
			// 	$seatkey ="seat".$i;
			// 	$cur_seatinfo =$info[$seatkey];
			// 	$info[$seatkey]=array(
			// 			'uid'=>$cur_seatinfo['uid'],
			// 			'seatid'=>$cur_seatinfo['seatid'],
			// 			'state'=>1,
			// 			'point'=>$cur_seatinfo['point'],
			// 		);
			// }
			//print_r($info);
			//$dachu['banker']=4;
			//print_r($dachu['throw_order']);
			//$seatkey="seat4";
			//$dachu = $this->redis->hGet(self::INFO_KEY.'67293121',$seatkey);			
			//$dachu =json_decode($dachu);
			// $all_seat =$dachu;
			// $dachu =$dachu->throw_front;
			// $all_seat->throw_front=array_push($dachu,4);
			// $all_seat['isHu']=1;
			// $all_seat['seat4']=array(1,2,2,5,5,6,9,9,11,14);
			//$dachu['throw_order']=json_encode(array('11'=>1,'21'=>3,'15'=>2,'1'=>1));
			// //print_r($dachu);
			//$this->redis->hMSet(self::INFO_KEY . '21961134',$dachu);
			// $seat_list["$seatkey"]=$cur_pai;
			//$upsert["$seatkey"]=  json_encode($seat_list);
			//$res=json_decode($dachu['seat4']);
			echo json_encode($dachu);
			//print_r($dachu);
	}
	public function chiAction(){
		$this->redis=RedisDB::factory('game');
		// $order = $this->redis->hGetAll(self::PLAYER_ORDER . '84858714');

		// print_r($order['order']);exit;
		$roomid=$_GET['roomid'];
		$mUser = new UserModel(1);
		$mGame = new ElephantajiangModel($mUser,$roomid);
		$mGame->getFindEat();
		//$res=$mGame->sumscore(4,array(9),3,array());
		//print_r($res);
	}

	public function indexAction() {
			$this->redis=RedisDB::factory('game');
			// $roomlist = $this->redis->hGetAll(self::INFO_KEY.'12775775');
			// $roomlist['owner']=1;
			// $this->redis->hMSet(self::INFO_KEY . '12775775', $roomlist);
			// $redis =RedisDB::factory('user');
			// $mUser = new UserModel(1);
			// $user = $mUser->getInfo();
			// foreach ($user as $key => $value) {
			// 	$redis->hDel('user:1',$key);
			// }
			
			
			// print_r($user);
			// $this->redis->hDel(self::INFO_KEY . '32217571','seat4');
			// $this->redis->hDel(self::INFO_KEY . '32217571','state');
			//$roomInfo = $this->redis->hGetAll(self::INFO_KEY . $user['roomid']);
			// $roomInfo=$roomInfo['watcher'];
			// $roomInfo =json_decode($roomInfo);
			// $arr=$this->object2array($roomInfo);
			// unset($arr[1]);
			// $thisroomInfo = json_decode($roomlist['22222']);
		//$roomlist = $this->redis->hGetAll(UserModel::USERNAME_KEY);
		//foreach($roomInfo as $key=>$value){
			//$this->redis->hDel(self::INFO_KEY .'22222', 'watcher');
			// if($key=='watcher'){
			// 	$vv=$this->objectToArr($value);
			// 	unset($vv[1]);
			// 	//print_r($vv);
			// 	if($vv){
			// 		echo '1';
			// 	}else{
			// 		$this->redis->hDel(self::INFO_KEY .'46684824', 'watcher');
			// 	}
			// }
		//}
		//print_r($roomInfo);
    	//$where=array('id' =>1);
   		//$user=new HbModel('gm_member');//直接实例化给表名就行了，其他跟操作thinkphp一样
		//$result = $user->where($where)->select();
		//echo $user->getlastsql();
		//print_r($result);
		exit;
	}
	function object2array(&$object) {
         $object =  json_decode( json_encode( $object),true);
         return  $object;
	}
	/**
	 * 创建房间
	 * [createAction description]
	 * @return [type] [description]
	 */
	public function  createAction(){
		//随机生成房间号
		$fromuser =isset($_COOKIE['openid'])?$_COOKIE['openid']:'';
		$time_way =isset($_POST['time_way'])&&intval($_POST['time_way'])==2?2:1;//1-时间 2- 牌局
		$setting_value =isset($_POST['time_value'])?intval($_POST['time_value']):15;//默认值15分钟
		$game_type =isset($_POST['game_type'])?$_POST['game_type']:'xizhou';
		//file_put_contents('./controllers/game.txt', $_GET['game_type'].PHP_EOL,FILE_APPEND);
		$double =isset($_POST['double'])?$_POST['double']:'1';//倍数1
		//判断数值是否符合
		$basic= array(1,2,3,4,15,20,30,60,90,150);
		if(!in_array($setting_value,$basic)){
			$response=array('message'=>$setting_value);
			$this->response(401,'传递数值不正确',$response);
		}
		$this->redis = RedisDB::factory('game');
		$roomlist = $this->redis->hGetAll(self::LIST_KEY);


		//print_r($roomlist);exit;
		//test
		// $this->redis=RedisDB::factory('game');
		// $redis =RedisDB::factory('user');
		// $mUser = new UserModel($this->mUser->getUid());
		// $user = $mUser->getInfo();
		// foreach ($user as $key => $value) {
		// 	$redis->hDel('user:1','roomid');
		// 	$redis->hDel('user:1','seatid');
		// 	$redis->hDel('user:2','roomid');
		// 	$redis->hDel('user:2','seatid');
		// 	$redis->hDel('user:3','roomid');
		// 	$redis->hDel('user:3','seatid');
		// 	$redis->hDel('user:4','roomid');
		// 	$redis->hDel('user:4','seatid');
		// }
		// foreach ($roomlist as $key => $value) {
		// 	$this->redis->hDel(self::LIST_KEY,$key);
		// 	$all = $this->redis->hGetAll(self::PLAYER_ORDER . $key);
		// 	foreach($all as $allkey=>$v){
		// 		$this->redis->hDel(self::PLAYER_ORDER.$key,$allkey);
		// 	}
		// 	$dachu = $this->redis->hGetAll(self::INFO_KEY.$key);
		// 	foreach($dachu as $mykey=>$v){
		// 		$this->redis->hDel(self::INFO_KEY.$key,$mykey);
		// 	}
			
		// }

		$iscan_create=1;
		if(is_array($roomlist) && $roomlist){
			foreach ($roomlist as $key => $value) {
				$result =json_decode($value);
				if(!isset($result->created)) continue;
				$that_createdtime=$result->created;
				if($fromuser==$result->fromuser && time() < $that_createdtime+60*self::VALID_TIME){
					$iscan_create=2;
					$roomid=$key;
					break;
				}
			}
		}
		if($iscan_create==2){
			$response=array('roomid'=>$roomid,'fromuser'=>$fromuser);
			$this->response(401,'已经创建房间号了',$response);//20427494
			exit;
		}

		// foreach ($roomlist as $key => $value) {
		// 	$this->redis->hDel(self::LIST_KEY,$key);
		// }
		// exit;
		// if(is_array($roomlist) && $roomlist){
		// 	print_r($roomlist);exit;
		// }
		do{	
			//$id = mt_rand(10000000, 99999999);
			$id =$this->random();
			$save_data=array('fromuser'=>$fromuser,'created'=>time(),'time_way'=>$time_way,'setting_value'=>$setting_value,'game_type'=>$game_type);
			$ret = $this->redis->hSetNx(self::LIST_KEY,$id,json_encode($save_data));
			if(!$ret){
				continue;
			}
			
			break;
		}while(true);
		//创建房间信息
		$this->roomInfo($id,$setting_value,$time_way);
		//file_put_contents('./controllers/room.txt', $id.PHP_EOL,FILE_APPEND);
		$response=array('roomid'=>$id,'fromuser'=>$fromuser);
		$this->response(200,'创建房间号',$response);
	}
	//保存房间号
	private function roomInfo($id,$time_value,$time_way){		
		$this->id = $id;
		$this->info = array(
			'id' => $id,
			'owner' => '',//房主
			'time' => time(),//创建时间
			'state' => 0,//状态
			'point' => 0,//积分
			'pan'=>0,
			'quan'=>1,
			'present_quan'=>1,//目前东风圈
			'time_value'=>$time_value,
			'time_way'=>$time_way,
		);
		$this->redis->hMSet(self::INFO_KEY . $id, $this->info);
	}
	private function random($type=1,$number=8){
		$string=''; 
		for($i = 1; $i <= $number; $i++){ 
			//混合 
			$panduan=1; 
			if($type == 3){ 
				if(rand(1,2)==1){ 
					$type=1; 
				}else{ 
					$type=2; 
				} 
				$panduan=2; 
			} 

			//数字 
			if($type==1){
				$string.=rand(0,9); 
			}elseif($type==2){ 
				//字母 
				$rand=rand(0,24); 
				$b='a'; 
				for($a =0;$a <=$rand;$a++){ 
					$b++; 
				} 
				$string.=$b; 
			} 
			if($panduan==2)$type=3; 
		}
		return $string; 
	}
}